<template>
  <div class="timer">
    <span v-if="year>0">{{year}}&nbsp;year&nbsp;&nbsp;</span>
    <span>{{day}}&nbsp;days&nbsp;&nbsp;</span>
    <span>{{hour}}:</span>
    <span>{{minute}}:</span>
    <span>{{second}}</span>
  </div>
</template>

<script setup name="Timer">
import moment from 'moment'
import { onMounted, onUnmounted, ref } from 'vue'

const year = ref("");
const day = ref("");
const hour = ref("");
const minute = ref("");
const second = ref("");
let tiemInterval = ref("");

const limitFormatTime = (timestamp) =>{
  let time = moment().diff(moment("2022-11-10"))/1000;
  var y = Math.floor(time / 3600 / 24 / 365),
      d = Math.floor((time / 3600 / 24)%365),
      h = Math.floor((time / 3600) % 24),
      m = Math.floor((time % 3600) / 60),
      s = Math.floor((time % 3600) % 60);
  if (h < 10) {
      h = "0" + h;
  }
  if (m < 10) {
      m = "0" + m;
  }
  if (s < 10) {
      s = "0" + s;
  }
  return {
    y: y, // 年
    d: d, // 天
    h: h, // 时
    m: m, // 分
    s: s // 秒
  }
}
onMounted(()=>{
  tiemInterval = setInterval(()=>{
    let limit = limitFormatTime();
    year.value = limit.y;
    day.value = limit.d;
    hour.value = limit.h;
    minute.value = limit.m;
    second.value = limit.s;
  },1000)
})
onUnmounted(()=> {
  clearInterval(tiemInterval);
})
</script>

<style lang="scss" scoped>
.timer {
  box-sizing: border-box;
  padding: 0 25px;
  color: #eee;
  font-family: UnidreamLED;
  letter-spacing: 3px;
  background: #000000B3;
  border-radius: 8px;
}
</style>